package com.hancai.barrage.service.impl;

import com.hancai.barrage.mapper.EmployeeMapper;
import com.hancai.barrage.model.LoginInfo;
import com.hancai.barrage.model.Page;
import com.hancai.barrage.pagehelper.QueryObject;
import com.hancai.barrage.pojo.Employee;
import com.hancai.barrage.service.SysEmployeeService;
import com.hancai.barrage.utils.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author 涵菜
 * @version 1.0
 */
@Slf4j
@Service
public class EmployeeServiceImpl implements SysEmployeeService {
    private final EmployeeMapper employeeMapper;

    public EmployeeServiceImpl(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }

    @Override
    public void save(Employee obj) {
        employeeMapper.insert(obj);
    }

    @Override
    public void updateById(Employee obj) {
        employeeMapper.updateByPrimaryKey(obj);
    }

    @Override
    public void deleteById(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
     return employeeMapper.selectAll();
    }

    @Override
    public Page<Employee> query(QueryObject qo) {
        long total=employeeMapper.selectCount(qo);
        if(total==0){
            return Page.empty(qo.getPageNum(),qo.getPageSize());
        }
        List<Employee> employees=employeeMapper.selectForList(qo);
        return new Page<>(qo.getPageNum(),qo.getPageSize(),total,employees);
    }

    @Override
    public String login(String username, String password) {
        //1，跟据用户名去查看用户信息
        Employee employee=employeeMapper.selectByUsername(username);
        //2，如果信息不存在，提示用户名或者密码错误
        if(username==null){
            log.error("[员工服务]登陆失败，用户名输入错误，用户={}",username);
            throw new RuntimeException("用户名错误");
        }
        //3，判断密码是否正确
        if(!password.equals(employee.getPassword())){
            log.error("[员工服务]登陆失败，密码输入错误，用户={},提交的密码={}",username,password);
            throw new RuntimeException("用户名或密码错误");
        }
        //4，生成token，并将当前用户存入map集合
        String token = TokenManager.getToken();

        LoginInfo loginInfo = new LoginInfo();
        //将employee对象中所有与loginInfo对象中属性名相同的属性值，全部复制到loginInfo
        BeanUtils.copyProperties(employee,loginInfo);

//        BeanInfo beanInfo = Introspector.getBeanInfo(loginInfo.class);
//        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
//        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
//            Method writeMethod = propertyDescriptor.getWriteMethod();
//            Method readMethod = propertyDescriptor.getReadMethod();
//        }
        TokenManager.setInfo(token,loginInfo);
        //5，返回token
        return token;
    }
}
